package com.zone.service.controller;
import com.zone.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Map;

@RestController
public class FileUploadController {
    @Value("${ruoyi.profile}")
    private String profile;
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file,
                             @RequestParam(defaultValue = "profile") String type) {
        try {
            String originalName = file.getOriginalFilename();
            if (originalName == null || !originalName.contains(".")) {
                return AjaxResult.error("文件名非法");
            }

            String ext = originalName.substring(originalName.lastIndexOf('.') + 1).toLowerCase();
            if (!"jpg".equals(ext) && !"jpeg".equals(ext) && !"png".equals(ext)) {
                return AjaxResult.error("仅支持 jpg/png/jpeg");
            }
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("文件不能超过 5MB");
            }

            String date = LocalDate.now().toString();
            String fileName = System.currentTimeMillis() + "." + ext;

            //String relative = "profile/" + date + "/" + fileName;
            String relative = type + "/" + date + "/" + fileName;

            Path dest = Paths.get(profile, relative);
            Files.createDirectories(dest.getParent());
            file.transferTo(dest.toFile());
            String url = "/" + relative.replace("\\", "/");

            return AjaxResult.success(Map.of(
                    "url", url,
                    "fileName", fileName,
                    "type", type
            ));
        } catch (Exception e) {
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }
}
